package com.duoec.doc.service.impl;

import com.duoec.doc.dao.ApiDao;
import com.duoec.doc.entity.ApiEntity;
import com.duoec.doc.service.ApiService;
import com.duoec.doc.service.DocService;
import com.mongodb.client.model.Filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xuwenzhen
 * @date 19/1/21
 */
@Service
public class ApiServiceImpl implements ApiService {
    private static final Logger logger = LoggerFactory.getLogger(ApiServiceImpl.class);
    private static final String STR_KEY = "key";
    private static final String DOC_ID = "docId";
    private static final String STR_METHOD = "methods";
    private static final String STR_PATHS = "paths";

    @Autowired
    private ApiDao apiDao;

    @Autowired
    private DocService docService;

    /**
     * 通过apiKey找到某个站点的api
     *
     * @param siteId 站点ID
     * @param apiKey 接口ID
     * @return 对应的api，如果找不到则返回null
     */
    @Override
    public ApiEntity getApi(String siteId, String apiKey) {
        return apiDao.find(Filters.and(
//                Filters.eq(STR_SITE, siteId), //TODO 需要修复
                Filters.eq(STR_KEY, apiKey)
        )).first();
    }

    /**
     * 通过appId和mapping，找到对应的RestFul接口
     *
     * @param appId  应用ID
     * @param path   mapping
     * @param method 使用的方法
     * @return 对应的api，如果找不到则返回null
     */
    @Override
    public ApiEntity getRestApiByPath(String appId, String path, String method) {
        String docId = docService.getDocIdByAppId(appId);
        if (docId == null) {
            logger.warn("无法找到appId={}对应的项目", appId);
            return null;
        }
        ApiEntity api = apiDao.find(Filters.and(
                Filters.eq(DOC_ID, docId),
                Filters.eq(STR_PATHS, path),
                Filters.or(
                        Filters.eq(STR_METHOD, method),
                        Filters.exists(STR_METHOD, false)
                )
        )).first();
        if (api != null) {
            return api;
        }

        return apiDao.find(Filters.and(
                Filters.eq(STR_PATHS, path),
                Filters.or(
                        Filters.eq(STR_METHOD, method),
                        Filters.exists(STR_METHOD, false)
                )
        )).first();
    }
}
